package com.ccc.netty.server.splitpacket.handler;

import com.ccc.netty.server.splitpacket.pojo.MyMsgProtocol;
import com.ccc.netty.server.splitpacket.util.MyHexUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 自定义长度分包解码器
 *
 * @author superC
 * @version 1.0.0
 * @date 2022/8/20
 */

public class MyLengthFieldDecoder extends ByteToMessageDecoder {

    // 临时统计拆包个数
    int count = 0;

    String startId = "";
    Integer type = null;
    int length = 0;
    Integer id = null;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println();
        System.out.println("=========接收报文数据");
        System.out.println(in);
        count++;

        if (in.readableBytes() >= 16) {
            if ("".equals(startId)) {
                byte[] arr = new byte[4];
                in.readBytes(arr);
                startId = MyHexUtils.asciiToStr(arr);
                System.out.println("=======起始标识符为：" + startId);
            }
            if (type == null) {
                type = in.readInt();
                System.out.println("=======消息类型为：" + type);
            }
            if (length == 0) {
                length = in.readInt();
                System.out.println("=======数据体长度为：" + length);
            }
            if (id == null) {
                id = in.readInt();
                System.out.println("=======消息序列号为：" + id);
            }

            if (in.readableBytes() < length) {
                System.out.println("当前可读数据不够，继续等待。。");
                return;
            } else {
                byte[] content = new byte[length];
                in.readBytes(content);

                MyMsgProtocol myMsgProtocol = new MyMsgProtocol(startId, type, length, id, content);

                // 传递到下一个handler业务处理
                out.add(myMsgProtocol);

                System.out.println("=======***************拆包次数为：" + count);

                // 归位
                length = 0;
                count = 0;
                startId = "";
                type = null;
                id = null;
            }
        }
    }

}